package com.flowplan.ai.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * 通义千问API客户端
 * 
 * @author FlowPlan Team
 */
@Slf4j
@Component
public class TongyiClient {
    
    @Value("${ai.tongyi.api-key}")
    private String apiKey;
    
    @Value("${ai.tongyi.base-url}")
    private String baseUrl;
    
    @Value("${ai.tongyi.model}")
    private String model;
    
    @Value("${ai.tongyi.timeout}")
    private int timeout;
    
    private final RestTemplate restTemplate;
    
    public TongyiClient() {
        this.restTemplate = new RestTemplate();
    }
    
    /**
     * 发送聊天请求
     */
    public TongyiResponse sendChatRequest(String prompt) {
        return sendChatRequest(prompt, null);
    }
    
    /**
     * 发送聊天请求（带历史对话）
     */
    public TongyiResponse sendChatRequest(String prompt, List<ChatMessage> history) {
        try {
            log.info("发送通义千问请求: {}", prompt);
            
            // 构建请求消息
            List<ChatMessage> messages = new ArrayList<>();
            if (history != null && !history.isEmpty()) {
                messages.addAll(history);
            }
            messages.add(new ChatMessage("user", prompt));
            
            // 构建请求体
            TongyiRequest request = TongyiRequest.builder()
                    .model(model)
                    .messages(messages)
                    .temperature(0.7f)
                    .maxTokens(2000)
                    .topP(0.8f)
                    .build();
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(apiKey);
            
            HttpEntity<TongyiRequest> httpEntity = new HttpEntity<>(request, headers);
            
            // 发送请求
            ResponseEntity<TongyiResponse> response = restTemplate.postForEntity(
                    baseUrl, httpEntity, TongyiResponse.class);
            
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                log.info("通义千问请求成功");
                return response.getBody();
            } else {
                log.error("通义千问请求失败: {}", response.getStatusCode());
                return TongyiResponse.error("API请求失败");
            }
            
        } catch (Exception e) {
            log.error("调用通义千问API异常: {}", e.getMessage(), e);
            return TongyiResponse.error("API调用异常: " + e.getMessage());
        }
    }
    
    /**
     * 需求分析
     */
    public TongyiResponse analyzeRequirements(String requirements) {
        String prompt = String.format(
                "请分析以下需求内容，提取关键信息并生成结构化的分析结果：\n\n%s\n\n" +
                "请按以下格式返回分析结果：\n" +
                "1. 需求概述\n" +
                "2. 核心功能点\n" +
                "3. 技术要求\n" +
                "4. 风险点分析\n" +
                "5. 建议的实施步骤",
                requirements
        );
        
        return sendChatRequest(prompt);
    }
    
    /**
     * 生成功能设计文档
     */
    public TongyiResponse generateFunctionSpec(String requirement) {
        String prompt = String.format(
                "基于以下需求，生成详细的功能设计文档：\n\n%s\n\n" +
                "请按以下结构生成文档：\n" +
                "# 功能设计文档\n\n" +
                "## 1. 功能概述\n" +
                "## 2. 功能详细说明\n" +
                "## 3. 接口设计\n" +
                "## 4. 数据结构\n" +
                "## 5. 业务流程\n" +
                "## 6. 异常处理\n" +
                "## 7. 测试要点",
                requirement
        );
        
        return sendChatRequest(prompt);
    }
    
    /**
     * 生成测试用例
     */
    public TongyiResponse generateTestCases(String functionality) {
        String prompt = String.format(
                "基于以下功能描述，生成详细的测试用例：\n\n%s\n\n" +
                "请按以下格式生成测试用例：\n" +
                "## 测试用例设计\n\n" +
                "### 1. 正常流程测试\n" +
                "### 2. 异常流程测试\n" +
                "### 3. 边界值测试\n" +
                "### 4. 性能测试\n" +
                "### 5. 安全测试\n\n" +
                "每个测试用例包含：\n" +
                "- 测试场景\n" +
                "- 前置条件\n" +
                "- 测试步骤\n" +
                "- 预期结果",
                functionality
        );
        
        return sendChatRequest(prompt);
    }
    
    /**
     * 智能建议
     */
    public TongyiResponse getSmartSuggestions(String context) {
        String prompt = String.format(
                "基于以下项目上下文，提供智能建议：\n\n%s\n\n" +
                "请从以下角度提供建议：\n" +
                "1. 项目管理建议\n" +
                "2. 技术实现建议\n" +
                "3. 风险预警\n" +
                "4. 优化建议\n" +
                "5. 最佳实践推荐",
                context
        );
        
        return sendChatRequest(prompt);
    }
    
    /**
     * 聊天消息类
     */
    public static class ChatMessage {
        private String role;
        private String content;
        
        public ChatMessage() {}
        
        public ChatMessage(String role, String content) {
            this.role = role;
            this.content = content;
        }
        
        public String getRole() { return role; }
        public void setRole(String role) { this.role = role; }
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
    }
}